package mrusanov.images

import java.awt.image.BufferedImage
import com.sixlegs.png.PngImage
import java.io.File
import javax.imageio.ImageIO
import xml.XML

object ImageCache {
  private var cache:Map[String, BufferedImage] = Map()

  private [images] def get(path:String):BufferedImage = {
    if (cache.contains(path)) {
      return cache(path)
    }

    val image = loadImage(path)
    cache += (path -> image)
    image
  }

  private def loadImage(path:String):BufferedImage = {
    val correctPath = Option(getClass.getResource(path)).map(_.toURI)

    if (correctPath.isEmpty) {
      throw new IllegalArgumentException("Not able to load image using path: " + path)
    }

    val file = new File(correctPath.get)

    if (path.endsWith("png")) {
      new PngImage().read(file)
    } else {
      ImageIO.read(file)
    }
  }
}
